package com.doit.day01;

import lombok.*;

import java.sql.*;
import java.util.Iterator;

public class MysqlIterator implements Iterator<UserInfo> {
    private ResultSet resultSet;
    //需要做的事情是什么
    //获取mysql的连接
    //去表中读取数据
    public MysqlIterator() throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        PreparedStatement pps = conn.prepareStatement("select * from user_info");
        resultSet = pps.executeQuery();
    }

    @Override
    public boolean hasNext() {

        boolean flag = false;
        try {
             flag = resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public UserInfo next() {
        UserInfo userInfo = new UserInfo();
        try {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            int age = resultSet.getInt(3);
            String gender = resultSet.getString(4);
            userInfo.setAge(age);
            userInfo.setGender(gender);
            userInfo.setId(id);
            userInfo.setName(name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userInfo;
    }
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
class UserInfo{
    private int id;
    private String name;
    private int age;
    private String gender;
}
